<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收缩菜单</title>
    <link rel="stylesheet" href="./css/index.css">
    <style>
        .active {
            background-color: rgb(24, 144, 255);
            color: white !important;
        }
    </style>
</head>

<body>
    <div class="menu-wraper">
        <h2>新闻管理</h2>
        <ul>
            <li>新闻</li>
            <li>娱乐</li>
            <li>NBA</li>
            <li>体育</li>
        </ul>

        <h2>用户管理</h2>
        <ul>
            <li>用户列表</li>
            <li>添加用户</li>
            <li>设备管理</li>
        </ul>
    </div>

    <script>
        function onTitleMenu() {
            const h2s = document.querySelectorAll('.menu-wraper h2')
            for (let i = 0; i < h2s.length; i++) {
                h2s[i].onclick = function () {
                    const ul = this.nextElementSibling
                    //计算高度
                    const li = ul.firstElementChild
                    const count = ul.querySelectorAll('li').length
                    const totalHeight = li.offsetHeight * count
                    const height = window.getComputedStyle(ul).height
                    if (height == '0px') {
                        ul.style.height = totalHeight + 'px'
                    } else {
                        ul.style.height = '0px'
                    }
                }
            }

        }

        const liEles = document.querySelectorAll('.menu-wraper li')

        function clearActive() {
            for (let i = 0; i < liEles.length; i++) {
                liEles[i].classList.remove('active')
            }
        }

        function onTab() {
            for (let i = 0; i < liEles.length; i++) {
                liEles[i].onclick = function () {
                    clearActive()
                    this.classList.add('active')
                }
            }
        }
        onTitleMenu()
        onTab()
    </script>
</body>

</html>